# -*- coding: UTF-8 -*-

__author__ = 'B5B6CACE'

import urllib2
import json
import redis
import web


access_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&' \
             'appid=wx992037f0a32db788&' \
             'secret=842958c1ab8fe373675cdaf0701bdaef'
cache = redis.Redis('localhost')
db = web.database(dbn='mysql', db='weixin', user='root', pw='000000')


def get_access_token():
    """
    获取微信的操作Token

    先从redis中获取token，如果token过期了，就从新获取并且放到redis中
    :return:  Token
    """
    access_token = cache.get('access_token')
    if access_token is None:
        json_context = urllib2.urlopen(access_url).read()
        access_token = json.JSONDecoder().decode(json_context)['access_token']
        cache.set('access_token', access_token)
        cache.expire('access_token', 7200)
        print 'access_token is out  of date,now reget it'
    print 'access_token is:%s' % access_token
    return access_token

#
# class NetworkTools:
#     def __init__(self):
#         self.cache = redis.Redis('localhost')
#         self.db = web.database(dbn='mysql', db='weixin', user='root', pw='000000')
#
#     def getAccess_Token(self):
#         access_token = self.cache.get('access_token')
#         if access_token is None:
#             json_context = urllib2.urlopen(access_url).read()
#             access_token = json.JSONDecoder().decode(json_context)['access_token']
#             print 'access_token is out  of date,now request it'
#         print 'access_token is:%s' % access_token
#         return access_token
#
#     def getProblems(self):
#         problempool = [item.values() for item in self.db.select('question')]
#         return problempool
#
#     def set_cache(self, key, object):
#         self.cache.set(key, object)
#
#     def get_cache(self, key):
#         return self.cache.get(key)